<script setup>
import CardComponent from "@/components/CardComponent.vue";
import { Delete, Plus, Search, Edit, Picture } from '@element-plus/icons-vue'
import { manageGetAllCategory, manageGetAllSetMeal, manageQuerySetmealLikeByNameOrCategoryIdOrStatus, manageBatchDeleteSetMealsByIds, manageDeleteSetMealById, manageUpdateSetMealStatusById, manageGetSetMealById, manageUpdateSetMealById } from "@/api/manage";
import { formatOperateTime } from "@/utils/format";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const formValues = ref({
  name: '',
  categoryName: '',
  status: ''
})

const packageCategory = ref([])
const getAllCategory = async () => {
  const { result } = await manageGetAllCategory()
  packageCategory.value = result.filter(item => item.type === 2)
}
const setMealList = ref([])
const getAllSetMeal = async () => {
  const { result } = await manageGetAllSetMeal()
  setMealList.value = result
  // console.log(setMealList.value);
}
getAllSetMeal()
getAllCategory()

// 查询套餐
const querySetmealLikeByNameOrCategoryIdOrStatus = async () => {
  const { result } = await manageQuerySetmealLikeByNameOrCategoryIdOrStatus(formValues.value)
  setMealList.value = result
}

// 批量删除
const tableRef = ref(null)
const onBatchDeletePackages = async () => {
  const selectedRows = tableRef.value.getSelectionRows();
  const selectedRowIds = selectedRows.map(row => row.id);
  if (selectedRowIds.length === 0) return ElMessage.error('请选择需要删除的套餐')
  await manageBatchDeleteSetMealsByIds(selectedRowIds)
  getAllSetMeal()
}

// 根据id删除套餐
const onDeleteSetMeal = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该套餐？', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await manageDeleteSetMealById({ id })
    getAllSetMeal()
  } catch (e) {
    ElMessage.info('取消删除')
  }
}
// 根据id修改status
const onChangeStatus = async (id, status) => {
  const newStatus = status === 1 ? 2 : 1
  try {
    await manageUpdateSetMealStatusById({ id, status: newStatus })
    getAllSetMeal()
  } catch (e) {
    ElMessage.info('操作失败')
  }
}
// 打开修改套餐
const isShowDrawer = ref(false)
// 绑定表单数据
const changeFormValues = ref({
  id: '',
  name: '',
  categoryId: '',
  price: '',
  description: '',
  image: '',
})
const imageShow = ref('')
const beforeAvatarUpload = (file) => {
  imageShow.value = URL.createObjectURL(file.raw)
  changeFormValues.value.image = file.raw
}
const onChangePackage = async (id) => {
  isShowDrawer.value = true
  const { result } = await manageGetSetMealById({ id })

  changeFormValues.value.id = result.id
  changeFormValues.value.name = result.name
  changeFormValues.value.categoryId = result.categoryId
  changeFormValues.value.price = result.price
  changeFormValues.value.description = result.description
  changeFormValues.value.image = result.image
  imageShow.value = result.image

}

const onSubmitChangePackage = async () => {
  const { id, name, categoryId, price, description, image } = changeFormValues.value
  if (!name) {
    ElMessage.error('套餐名称不能为空')
    return
  }
  if (!categoryId) {
    ElMessage.error('请选择套餐分类')
    return
  }

  // 判断名字是否重复
  const isRepeat = setMealList.value.some(item => item.name === name && item.id !== id)
  if (isRepeat) {
    return ElMessage.error('套餐名称重复')
  }
  const fd = new FormData()
  // 判断有值再添加
  if (id) {
    fd.append('id', id)
  }
  if (name) {
    fd.append('name', name)
  }
  if (categoryId) {
    fd.append('categoryId', categoryId)
  }
  if (price) {
    fd.append('price', price)
  }
  if (description) {
    fd.append('description', description)
  }

  if (image) {
    fd.append('image', image)
  }
  await manageUpdateSetMealById(fd)
  ElMessage.success('修改成功')
  isShowDrawer.value = false
  getAllSetMeal()
}
</script>

<template>
  <div>
    <CardComponent :is-need-head=false card-height="500px">
      <div class="package-header">
        <div>
          <el-form inline :model="formValues">
            <el-form-item label="套餐名称:">
              <el-input placeholder="请填写套餐名称" v-model="formValues.name"></el-input>
            </el-form-item>
            <el-form-item label="套餐分类:">
              <el-select clearable v-model="formValues.categoryName" placeholder="请选择">
                <el-option v-for="(item, index) in packageCategory" :key="index" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="售卖状态:">
              <el-select clearable v-model="formValues.status" placeholder="请选择">
                <el-option label="启售" value="1"></el-option>
                <el-option label="停售" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="querySetmealLikeByNameOrCategoryIdOrStatus">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="danger" :icon="Delete" @click="onBatchDeletePackages">批量删除</el-button>
          <el-button type="warning" :icon="Plus" @click="$router.push('/addPackage')">新建套餐</el-button>
        </div>
      </div>
      <div>
        <el-table :data="setMealList" ref="tableRef">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="套餐名称" prop="name" width="140"></el-table-column>
          <el-table-column label="图片" width="70">
            <template #default="{ row }">
              <el-image style="width: 30px; height: 30px;" :src="row.image || ''" fit="cover"
                :preview-src-list="[row.image]" preview-teleported>
                <template #error>
                  <div class="image-viewer-slot image-slot">
                    <el-icon :size="30">
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="套餐分类" prop="categoryName" width="140"></el-table-column>
          <el-table-column label="套餐价" width="100">
            <template #default="{ row }">
              {{ `￥${row.price}` }}
            </template>
          </el-table-column>
          <el-table-column label="售卖状态" width="140">
            <template #default="{ row }">
              {{ row.status === 1 ? "在售" : "停售" }}
            </template>
          </el-table-column>
          <el-table-column label="最后操作时间" width="140">
            <template #default="{ row }">
              {{ formatOperateTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" class-name="operation-column">
            <template #default="{ row }">
              <el-button type="primary" :icon="Search" @click="onChangePackage(row.id)">修改</el-button>
              <el-button type="danger" :icon="Delete" @click="onDeleteSetMeal(row.id)">删除</el-button>
              <el-button type="warning" :icon="Edit" v-if="row.status === 1"
                @click="onChangeStatus(row.id, row.status)">禁用</el-button>
              <el-button type="success" :icon="Edit" v-else @click="onChangeStatus(row.id, row.status)">启用</el-button>
              <el-button type="info" :icon="Plus"
                @click="$router.push(`/addPackageDish?packageId=${row.id}`)">指定菜品</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </CardComponent>
    <el-drawer title="修改套餐" v-model="isShowDrawer" size="50%">
      <el-form :model="changeFormValues">
        <el-form-item label="套餐名称:">
          <el-input v-model="changeFormValues.name"></el-input>
        </el-form-item>
        <el-form-item label="套餐类型:">
          <el-select placeholder="请选择" v-model="changeFormValues.categoryId">
            <el-option v-for="(item, index) in packageCategory" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格:">
          <el-input-number v-model="changeFormValues.price" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="套餐描述:">
          <el-input type="textarea" autosize v-model="changeFormValues.description"></el-input>
        </el-form-item>
        <el-form-item label="套餐图片">
          <el-upload class="avatar-uploader" :show-file-list="false" :on-change="beforeAvatarUpload"
            :auto-upload="false">
            <img v-if="imageShow" :src=imageShow class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitChangePackage">保存</el-button>
          <el-button @click="isShowDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
:deep(.el-input .el-input__wrapper) {
  width: 120px;
}

:deep(.el-select .el-select__wrapper) {
  width: 120px;
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form--inline .el-form-item {
  margin: 0 10px;
}

:deep(.operation-column .cell) {
  display: flex;
  gap: 10px
}

:deep(.operation-column .cell .el-button) {
  width: 60px;
}

:deep(.operation-column .cell .el-button:last-child) {
  width: 120px;
}

:deep(thead .operation-column .cell) {
  justify-content: center;
}


.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-drawer .el-select__wrapper) {
  width: 100%;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
